package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.commit.R;
import com.itheima.commit.CacheService;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private CacheService cacheService;

    @Override
    public R<String> send(User user, HttpServletRequest request) {
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
//            String code = ValidateCodeUtils.generateValidateCode(6).toString();
//            SMSUtils.sendMessage(phone,code);
            String code = "1234";
            log.info("code:{}",code);
            cacheService.setEx(phone,code,5, TimeUnit.MINUTES);
//            request.getSession().setAttribute(phone,code);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    @Override
    public R<User> login(Map map, HttpServletRequest request) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

//        String s = request.getSession().getAttribute(phone).toString();
        String s = cacheService.get(phone);

        if (s != null && s.equals(code)) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = this.getOne(wrapper);

            if (user == null) {
                user = new User();
                user.setPhone(phone);
                this.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            cacheService.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误");
    }
}
